package com.guli.gulimall.seckill.interceptor;

import com.guli.common.constant.AuthServerConstant;
import com.guli.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * order 全局拦截器，拦截未登录用户去登录
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 有些请求不需要登录，直接放行
         */
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);
        if (match) {
            HttpSession session = request.getSession();
            MemberResponseVo memberRsepVo = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            if (memberRsepVo != null) {
                loginUser.set(memberRsepVo);
                return true;
            } else {
                //没登录，重定向趣登录
                request.getSession().setAttribute("msg", "请先进行登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }
}
